package org.oschina.helper.redis;

import java.util.ArrayList;
import java.util.List;

import org.oschina.api.manage.cache.node.dao.CacheNodeDAO;
import org.oschina.api.manage.cache.node.vo.CacheNodeVo;
import org.oschina.util.jedis.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;

import redis.clients.jedis.ShardedJedisPool;

public class JedisHelper {

	@Autowired
	private CacheNodeDAO cacheNodeDAO;
	
	private static ShardedJedisPool jedisPool;
	private boolean inited=false;
	
	/**
	 * 初始化
	 * @param hosts
	 * @param maxActive
	 * @param maxIdle
	 * @param maxWait
	 * @param testOnBorrow
	 * @param testOnReturn
	 */
	private void initShardedJedisPool()
	{
		List<String> hosts=new ArrayList<String>();
		List<String> ports=new ArrayList<String>();
		List<CacheNodeVo> cacheNodes=cacheNodeDAO.findVo();
		for(CacheNodeVo cacheNode:cacheNodes)
		{
			hosts.add(cacheNode.getHost());
			ports.add(cacheNode.getPort());
		}
		
		jedisPool=JedisUtil.getShardedJedisPool(hosts, ports, maxActive, maxIdle, maxWait, testOnBorrow, testOnReturn);
	}
	
	public void refresh()
	{
		initShardedJedisPool();
	}
	
	public ShardedJedisPool getShardedJedisPool()
	{
		if(!inited)
		{
			initShardedJedisPool();
			inited=true;
		}
		
		return jedisPool;
	}
	
	/**
	 * 最大分配对象数
	 */
	private int maxActive;
	/**
	 * 最大能保持idle状态的数量
	 */
	private int maxIdle;
	/**
	 * 最大等待时间
	 */
	private int maxWait;
	/**
	 * 当调用return Object方法时，是否进行有效性检查
	 */
	private boolean testOnBorrow;
	private boolean testOnReturn;

	public int getMaxActive() {
		return maxActive;
	}
	public int getMaxIdle() {
		return maxIdle;
	}
	public int getMaxWait() {
		return maxWait;
	}
	public boolean isTestOnBorrow() {
		return testOnBorrow;
	}
	public boolean isTestOnReturn() {
		return testOnReturn;
	}
	public void setMaxActive(int maxActive) {
		this.maxActive = maxActive;
	}
	public void setMaxIdle(int maxIdle) {
		this.maxIdle = maxIdle;
	}
	public void setMaxWait(int maxWait) {
		this.maxWait = maxWait;
	}
	public void setTestOnBorrow(boolean testOnBorrow) {
		this.testOnBorrow = testOnBorrow;
	}
	public void setTestOnReturn(boolean testOnReturn) {
		this.testOnReturn = testOnReturn;
	}
	
}